package com.mazaiting.dtp.listeners;

import com.dtp.common.dto.NotifyPlatform;
import com.mazaiting.dtp.listeners.event.EmailEvent;
import com.mazaiting.mail.api.IMailSendFeignClient;
import com.mazaiting.mail.dto.MailAlarmDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;

/**
 * 邮件监听
 *
 * @author mazaiting
 * @create_time 2022/10/6 17:18
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class EmailListener implements ApplicationListener<EmailEvent> {

    private final IMailSendFeignClient mailSendFeignClient;

    @Override
    public void onApplicationEvent(@NonNull EmailEvent event) {
        NotifyPlatform platform = event.getPlatform();
        // 接收者
        String receivers = platform.getReceivers();
        if (StringUtils.hasLength(receivers)) {
            // 接收人
            List<String> list = Arrays.stream(receivers.split(",")).toList();
            // 取第一个位接收者, 剩下的为抄送人
            String receiver = list.get(0);
            // 抄送列表
            String cc = String.join(",", list.subList(1, list.size()));
            MailAlarmDTO mailAlarmDTO = new MailAlarmDTO();
            mailAlarmDTO.setMailId(1L);
            // 0 代表系统
            mailAlarmDTO.setPlatform(0);
            mailAlarmDTO.setReceiver(receiver);
            mailAlarmDTO.setCc(cc);
            mailAlarmDTO.setTitle("动态线程池");
            mailAlarmDTO.setContent(event.getContent());
            mailAlarmDTO.setHtml(true);
            mailSendFeignClient.alarm(mailAlarmDTO);
        }
    }
}
